package com.evil.formula.service.impl;

import com.evil.formula.antlr4.FormulaBaseVisitor;
import com.evil.formula.antlr4.FormulaLexer;
import com.evil.formula.antlr4.FormulaParser;
import com.evil.formula.api.RemoteFormulaService;
import com.evil.formula.pojo.dto.CalcReqDTO;
import com.evil.formula.pojo.dto.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liyang
 * @date 2023-10-30 17:27
 */
@Slf4j
@RestController
@AllArgsConstructor
public class FormulaServiceImpl implements RemoteFormulaService {

    /**
     * 公式计算
     *
     * @param calcReqDTO calcReqDTO
     */
    @Override
    public Result<?> calc(CalcReqDTO calcReqDTO) {
        String formula = calcReqDTO.getFormula();
        // 构造一个字符流
        CodePointCharStream codePointCharStream = CharStreams.fromString(formula);
        FormulaLexer formulaLexer = new FormulaLexer(codePointCharStream);
        // 用词法分析器 lexer 构造一个记号流 tokens
        CommonTokenStream tokens = new CommonTokenStream(formulaLexer);
        // 再使用 tokens 构造语法分析器 parser,至此已经完成词法分析和语法分析的准备工作
        FormulaParser parser = new FormulaParser(tokens);
        // 最终调用语法分析器的规则 parse（在demo.g4里定义的规则），完成对表达式的验证
        FormulaParser.FormulaContext context = parser.formula();

        Object visit = new FormulaBaseVisitor().visit(context);
        return null;
    }
}
